package servlet;

import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name="HolloServlet", urlPatterns="/hollo")

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
        List<User> use= new ArrayList<>();
        try {

            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接

            String url = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
            Connection connection = DriverManager.getConnection(url, "root", "200522");
            if(connection !=null){
                System.out.println("连接成功");
            }
            //3.写sql
            String sql="select *from user";
            //3.获取执行sql的对象
            PreparedStatement de=connection.prepareStatement(sql);
            ResultSet ui=de.executeQuery();
//            4.预编译sql

            //5.有参数设置参数
            //6.执行sql

            //7.遍历结果集
            while(ui.next()){
                User u=new User(ui.getInt("id"),ui.getString("name"),ui.getString("password"));

               use.add(u);
            }
            //8.关闭资源
            de.close();
            ui.close();
            connection.close();
            //把集合中的数据存储到作用域中
            req.setAttribute("user",use);
            //打开页面
            req.getRequestDispatcher("/user.jsp").forward(req,resp);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}